package wetalk.software.bupt.com.wetalk.view.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.message.MessageConfig;
import com.jyt.util.MySerializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.GloableParams;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.adapter.ContactAdapter;
import wetalk.software.bupt.com.wetalk.application.MyApplication;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClient;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.MyPinyinParser;
import wetalk.software.bupt.com.wetalk.util.PinyinComparator;
import wetalk.software.bupt.com.wetalk.util.WeTalkNetUtil;
import wetalk.software.bupt.com.wetalk.view.activity.GroupListActivity;
import wetalk.software.bupt.com.wetalk.view.activity.NewFriendsActivity;
import wetalk.software.bupt.com.wetalk.view.activity.UserInfoActivity;
import wetalk.software.bupt.com.wetalk.view.viewinter.MyLetterView;
import wetalk.software.bupt.com.wetalk.widget.ClearEditText;

/**
 * 通讯录Fragment
 */

public class Fragment_Friends extends Fragment implements View.OnClickListener{
    private View layout, layout_head;
    private ListView lvContact;

    private MyLetterView myLetterView;
    private TextView mDialogText;
    private ClearEditText mClearEditText;
    private Activity mActivity;
    private Context mContext;
    private boolean isInitData=false;

    //汉字转换为拼音的类
    private MyPinyinParser pinyinParser=new MyPinyinParser();
    private LayoutInflater inflater;
    private List<User> userList=null;//朋友信息
    private ContactAdapter adapter;//通讯录listview的适配器

    private static final String TAG="Fragment_Friends";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG,"onCreateView执行了");

        this.inflater=inflater;
        layout = inflater.inflate(R.layout.fragment_friends, null);
        mActivity = getActivity();
        mContext = getContext();

        initViews();
        initFris();
        initData();
        setOnListener();
        return layout;
    }

    /**
     * 检测是否删除或添加了好友，并进行更新
     */
    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG,"onStart执行了");
        updateData();
    }

    /**
     * 初始化数据，和onCreateView里的initData方法互补
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d(TAG,"onHiddenChanged执行了");
        if(hidden){
            return;
        }else{
            updateData();
        }
    }

    private void updateData(){
        //如果数据没有初始化成功，就在这里初始化
        SharedPreferences.Editor editor=MyApplication.getContext().getSharedPreferences("data",Context.MODE_PRIVATE).edit();
        SharedPreferences pref= MyApplication.getContext().getSharedPreferences("data",Context.MODE_PRIVATE);
        String isDisplay=pref.getString("display","");
        String isAdd=pref.getString("isAdd","");
        String isDel=pref.getString("isDel","");

        if(isDisplay.equals("yes")){//判断是否初始化了数据，
            userList=WeTalkDB.create(mContext).queryFriList();
            if(userList!=null && userList.size()!=0){
                Collections.sort(userList,new PinyinComparator());
                adapter=new ContactAdapter(getActivity(),userList);
                lvContact.setAdapter(adapter);
            }
            Log.d(TAG,"初始化数据成功");
            editor.putString("display","no");
            editor.apply();
        }

        if(isAdd.equals("yes")){//判断是否添加了好友，有则更新好友列表
            Log.d(TAG,"onStart-->"+"添加了好友，重新加载数据库");
            this.userList=WeTalkDB.create(MyApplication.getContext()).queryFriList();
            if(userList!=null&&userList.size()!=0){
                Collections.sort(userList,new PinyinComparator());
                adapter=new ContactAdapter(getActivity(),userList);
                lvContact.setAdapter(adapter);
            }
            //如果更新了好友列表，设置参数为no，表示下次执行该函数的时候不会再更新
            editor.putString("isAdd","no");
            editor.apply();
        }else{
            Log.d(TAG,"onStart-->"+"没有添加好友");
        }

        if(isDel!=null && isDel.equals("yes")){//判断是否删除了好友，有则更新好友列表
            Log.d(TAG,"onStart-->"+"删除了好友，重新加载数据库");
            this.userList=WeTalkDB.create(MyApplication.getContext()).queryFriList();
            if(userList!=null&&userList.size()!=0){
                Collections.sort(userList,new PinyinComparator());
                adapter=new ContactAdapter(getActivity(),userList);
                lvContact.setAdapter(adapter);
            }
            editor.putString("isDel","no");
            editor.apply();
        }else{
            Log.d(TAG,"onStart-->"+"没有删除好友");
        }

    }

    /**
     * 初始化界面
     */
    private void initViews() {
        lvContact = (ListView) layout.findViewById(R.id.lvContact);
        mDialogText = (TextView) layout.findViewById(R.id.tv_char);
        myLetterView=(MyLetterView) layout.findViewById(R.id.myletterview);
        myLetterView.setTextView(mDialogText);

        layout_head = inflater.inflate(R.layout.layout_head_friend, null);
        mClearEditText = (ClearEditText)layout.findViewById(R.id.et_msg_search);
        lvContact.addHeaderView(layout_head);
        adapter=new ContactAdapter(getActivity(),userList);
        lvContact.setAdapter(adapter);
    }


    /**
     * 发送拉取好友的请求。
     * 只会在第一次登陆时调用，以后不再使用。
     * (留了个后手，避免以后需要拉取好友，如果isSend为yes就可以再次发送请求)
     */
    private void initFris(){
        Log.d(TAG,"initFris执行了");
        SharedPreferences.Editor editor=MyApplication.getContext().getSharedPreferences("data",Context.MODE_PRIVATE).edit();
        SharedPreferences pref= MyApplication.getContext().getSharedPreferences("data",Context.MODE_PRIVATE);
        String isSend=pref.getString("isSendPull","");

        if(isSend!=""){//isSend不为空，则说明不是第一次拉取好友列表

            if(isSend.equals("yes")){//如果isSend的值为yes，说明就执行拉取好友操作

                if(WeTalkNetUtil.isNetworkAvailable(getContext())){//如果有网，则执行拉取好友操作
                    sendPull();
                    editor.putString("isSendPull","no");
                    editor.apply();
                }else{
                    Toast.makeText(mActivity, "当前无网络", Toast.LENGTH_SHORT).show();
                }
            }

        }else{//isSend为空，则说明是第一次登录，执行拉取好友列表操作

            if(WeTalkNetUtil.isNetworkAvailable(getContext())){//如果有网，则执行拉取好友操作
                sendPull();
                editor.putString("isSendPull","no");
                editor.apply();
            }else{
                Toast.makeText(mActivity, "当前无网络", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 初始化数据
     */
    private void initData(){
            userList=WeTalkDB.create(mContext).queryFriList();
            if(userList!=null && userList.size()!=0){
                Collections.sort(userList,new PinyinComparator());
                adapter=new ContactAdapter(getActivity(),userList);
                lvContact.setAdapter(adapter);
            }
    }

    /**
     * 设置监听器
     */
    private void setOnListener() {
        //设置好友目录的子项点击事件
        lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position-1>=0){
                    User user=userList.get(position-1);
                    UserInfoActivity.actionStart(getContext(),user,"look");
                }
            }
        });
        //设置侧边栏的点击事件
        myLetterView.setOnTouchingLetterChangedListener(new LetterListViewListener());
        //设置添加好友的点击事件
        layout_head.findViewById(R.id.layout_addfriend).setOnClickListener(this);
        //设置群聊的点击事件
        layout_head.findViewById(R.id.layout_group).setOnClickListener(this);
        //设置搜索框的文本改变事件
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filterData(s.toString());
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private class LetterListViewListener implements
            MyLetterView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(String s) {
            // 该字母首次出现的位置
            int position = adapter.getPositionForSelection(s.charAt(0));
            if (position != -1) {
                lvContact.setSelection(position);
            }
        }
    }


    /**
     *添加好友与群聊的点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_addfriend:// 添加好友
                Intent intent1=new Intent(getContext(), NewFriendsActivity.class);
                startActivity(intent1);
                break;

            case R.id.layout_group:// 群聊
                Intent intent = new Intent(mActivity,GroupListActivity.class);
                mContext.startActivity(intent);

            default:
                break;
        }
    }

    /**
     * 发送网络请求，拉取好友列表
     */
    private void sendPull(){
        final String userID= UserManager.getInstance(getContext()).getCurrentUserObjectId();
        new Thread(new Runnable() {
            @Override
            public void run() {
                AndroidClient client=new AndroidClient(GloableParams.ip, MessageConfig.server_name,userID,getContext());
                client.work();
                byte[] bs;
                bs = MySerializable.object_bytes("");
                Message msg = new Message(userID,"sys_friend","pullFri",bs);
                client.send(msg);
            }
        }).start();
        Log.d(TAG,"发送拉取好友列表请求");
    }


    /**
     * 搜索框文本改变事件
     */
    private void filterData(String filterStr) {
        List<User> filterDateList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = userList;
        } else {
            filterDateList.clear();
            for (User sortModel : userList) {
                String name = sortModel.getUserName();
                if (name != null) {
                    if (pinyinParser.toSimplePy(name).toLowerCase().contains(filterStr.toLowerCase())
                            || pinyinParser.toComplexPy(name).toLowerCase().contains(filterStr.toLowerCase())) {
                        filterDateList.add(sortModel);
                    }
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(filterDateList, new PinyinComparator());
        adapter.updateListView(filterDateList);
    }

}
